<template>
  <div class="detection-logs-container">
    <div class="page-header">
      <h2>检测日志管理</h2>
    </div>
    
    <!-- 搜索和筛选 -->
    <el-card class="search-card" shadow="hover">
      <el-form :model="searchForm" class="search-form">
        <el-form-item label="无人机ID">
          <el-input
            v-model="searchForm.drone_id"
            placeholder="请输入无人机ID"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item label="任务ID">
          <el-input
            v-model="searchForm.task_id"
            placeholder="请输入任务ID"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item label="检测目标ID">
          <el-input
            v-model="searchForm.detection_target_id"
            placeholder="请输入检测目标ID"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item label="检测结果">
          <el-select
            v-model="searchForm.is_positive"
            placeholder="选择检测结果"
            clearable
            size="small"
          >
            <el-option label="正样本" :value="true" />
            <el-option label="负样本" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否已处理">
          <el-select
            v-model="searchForm.processed"
            placeholder="选择处理状态"
            clearable
            size="small"
          >
            <el-option label="已处理" :value="true" />
            <el-option label="未处理" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item label="检测时间范围">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            size="small"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" size="small">
            <el-icon><component is="i-search" /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch" size="small">
            <el-icon><component is="i-refresh-left" /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 日志表格 -->
    <el-card class="logs-table-card" shadow="hover">
      <el-table
        :data="logsData"
        style="width: 100%"
        border
        v-loading="loading"
        element-loading-text="加载中..."
      >
        <el-table-column prop="id" label="ID" width="80" fixed />
        <el-table-column prop="drone_id" label="无人机ID" width="100" />
        <el-table-column prop="drone_name" label="无人机名称" width="150" show-overflow-tooltip />
        <el-table-column prop="task_id" label="任务ID" width="100" />
        <el-table-column prop="task_name" label="任务名称" width="150" show-overflow-tooltip />
        <el-table-column prop="target_name" label="检测目标" width="120" show-overflow-tooltip />
        <el-table-column label="检测位置" width="200">
          <template #default="{ row }">
            <div class="location-info">
              <div>经度: {{ row.longitude }}</div>
              <div>纬度: {{ row.latitude }}</div>
              <div>高度: {{ row.altitude }}m</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="confidence" label="置信度" width="100">
          <template #default="{ row }">
            <div>
              {{ row.confidence }}%
              <el-progress
                :percentage="row.confidence"
                :color="getProgressColor(row.confidence)"
                :height="6"
                :show-text="false"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="is_positive" label="检测结果" width="100">
          <template #default="{ row }">
            <el-tag :type="row.is_positive ? 'success' : 'warning'">
              {{ row.is_positive ? '正样本' : '负样本' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="processed" label="处理状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.processed ? 'info' : 'danger'">
              {{ row.processed ? '已处理' : '未处理' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="detection_time" label="检测时间" width="180" />
        <el-table-column prop="photo_time" label="拍照时间" width="180" />
        <el-table-column prop="photo_path" label="照片" width="120">
          <template #default="{ row }">
            <el-button
              v-if="row.photo_path"
              type="primary"
              size="small"
              link
              @click="viewPhoto(row.photo_path)"
            >
              查看
            </el-button>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="markAsProcessed(row.id)"
              v-if="!row.processed"
            >
              标记已处理
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="deleteLog(row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 照片查看对话框 -->
    <el-dialog
      v-model="photoDialogVisible"
      title="检测照片"
      width="80%"
      :before-close="handleClosePhotoDialog"
    >
      <img :src="currentPhotoUrl" alt="检测照片" style="max-width: 100%; max-height: 80vh;" />
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import axios from '../utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'DetectionLogs',
  setup() {
    const loading = ref(false)
    const searchForm = ref({
      drone_id: '',
      task_id: '',
      detection_target_id: '',
      is_positive: null,
      processed: null
    })
    const dateRange = ref([])
    const pagination = ref({
      currentPage: 1,
      pageSize: 10,
      total: 0
    })
    const logsData = ref([])
    const photoDialogVisible = ref(false)
    const currentPhotoUrl = ref('')

    // 获取检测日志数据
    const fetchLogs = async () => {
      loading.value = true
      try {
        const params = {
          page: pagination.value.currentPage,
          page_size: pagination.value.pageSize,
          drone_id: searchForm.value.drone_id,
          task_id: searchForm.value.task_id,
          detection_target_id: searchForm.value.detection_target_id
        }

        // 添加可选参数
        if (searchForm.value.is_positive !== null) {
          params.is_positive = searchForm.value.is_positive
        }
        if (searchForm.value.processed !== null) {
          params.processed = searchForm.value.processed
        }

        // 添加时间范围筛选
        if (dateRange.value && dateRange.value.length === 2) {
          params.start_time = dateRange.value[0]
          params.end_time = dateRange.value[1]
        }

        const response = await axios.get('/detection-logs', { params })
        if (response.code === 200) {
          logsData.value = response.data.items || []
          pagination.value.total = response.data.total || 0
        } else {
          ElMessage.error('获取检测日志失败')
        }
      } catch (error) {
        ElMessage.error('获取检测日志失败')
        console.error('获取检测日志失败:', error)
      } finally {
        loading.value = false
      }
    }

    // 处理搜索
    const handleSearch = () => {
      pagination.value.currentPage = 1
      fetchLogs()
    }

    // 重置搜索
    const resetSearch = () => {
      searchForm.value.drone_id = ''
      searchForm.value.task_id = ''
      searchForm.value.detection_target_id = ''
      searchForm.value.is_positive = null
      searchForm.value.processed = null
      dateRange.value = []
      pagination.value.currentPage = 1
      fetchLogs()
    }

    // 处理分页大小变化
    const handleSizeChange = (size) => {
      pagination.value.pageSize = size
      fetchLogs()
    }

    // 处理页码变化
    const handleCurrentChange = (current) => {
      pagination.value.currentPage = current
      fetchLogs()
    }

    // 获取进度条颜色
    const getProgressColor = (confidence) => {
      if (confidence >= 80) return '#67c23a'
      if (confidence >= 50) return '#e6a23c'
      return '#f56c6c'
    }

    // 查看照片
    const viewPhoto = (photoPath) => {
      // 构建照片URL（假设照片存储在static目录下）
      currentPhotoUrl.value = `/static/${photoPath}`
      photoDialogVisible.value = true
    }

    // 关闭照片对话框
    const handleClosePhotoDialog = () => {
      photoDialogVisible.value = false
      currentPhotoUrl.value = ''
    }

    // 标记为已处理
    const markAsProcessed = async (logId) => {
      try {
        const response = await axios.put(`/detection-logs/${logId}`, {
          processed: true
        })
        if (response.code === 200) {
          ElMessage.success('标记成功')
          fetchLogs()
        } else {
          ElMessage.error('标记失败')
        }
      } catch (error) {
        ElMessage.error('标记失败')
        console.error('标记失败:', error)
      }
    }

    // 删除日志
    const deleteLog = async (logId) => {
      try {
        await ElMessageBox.confirm(
          '确定要删除这条检测日志吗？',
          '警告',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        const response = await axios.delete(`/detection-logs/${logId}`)
        if (response.code === 200) {
          ElMessage.success('删除成功')
          fetchLogs()
        } else {
          ElMessage.error('删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
          console.error('删除失败:', error)
        }
      }
    }

    // 初始化
    onMounted(() => {
      fetchLogs()
    })

    return {
      loading,
      searchForm,
      dateRange,
      pagination,
      logsData,
      photoDialogVisible,
      currentPhotoUrl,
      handleSearch,
      resetSearch,
      handleSizeChange,
      handleCurrentChange,
      getProgressColor,
      viewPhoto,
      handleClosePhotoDialog,
      markAsProcessed,
      deleteLog
    }
  }
}
</script>

<style scoped>
.detection-logs-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: flex-end;
  gap: 16px;
}

.logs-table-card {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.location-info {
  font-size: 12px;
  line-height: 1.5;
}
</style>